package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {

    private static final String[] notCheckUri = {
            "/backend/**",
            "/front/**",
            "/employee/login",
            "/employee/logout",
            "/common/**",
            "/user/sendMsg",
            "/user/login",
            "/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
    };

    // spring提供的判断识别通配符的路径判断工具
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 1. 获取请求的uri
        String requestURI = req.getRequestURI();
        log.info("请求路径uri位：{}",requestURI);

        // 2. 校验需要过滤的请求
        boolean check = check(requestURI);

        // 3. 判断请求的uri是否需要放行
        if (!check) {
            log.info("请求路径uri: {}，是不需要过滤的路径",requestURI);
            chain.doFilter(req,resp);
            return;
        }

        // 4. 判断是否登陆  --> 服务端
        if (req.getSession().getAttribute("employee") != null) {
            log.info("用户已经登陆，不需要进行过滤");

            // 获取当前登陆的用户id
            Long id = (Long) req.getSession().getAttribute("employee");

            // 将当前用户id 保存到线程变量中
            BaseContext.setCurrentId(id);

            chain.doFilter(req,resp);

            // 访问结束，销毁线程变量中的数据
            BaseContext.removeCurrentId();

            return;
        }

        // 5. 判断是否登陆  --> 移动端
        if (req.getSession().getAttribute("user") != null) {

            log.info("判断移动端的登陆验证");

            // 获取当前用户id
            Long id = (Long) req.getSession().getAttribute("user");

            BaseContext.setCurrentId(id);

            chain.doFilter(req,resp);

            BaseContext.removeCurrentId();

            return;

        }

        // 5. 拦截请求，响应数据
        log.info("用户既不是静态资源，也没有登陆，请求路劲uri: {}，时需要先登陆",requestURI);
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 校验路径
     * @param requestURI
     * @return true 表示  需要进行校验
     *          false 表示  不需要进行校验
     */
    private boolean check(String requestURI) {
        // 遍历不要拦截的数据
        for (String uri : notCheckUri) {
            if (PATH_MATCHER.match(uri,requestURI)){
                // 条件成立表示请求路径是不需要进行过滤的
                return false;
            }
        }
        return true;
    }
}
